package com.sfc.sdsr.dao;

import java.io.File;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DaoVerifier extends SQLiteOpenHelper {

	private final String TAG = getClass().getSimpleName();
	private final String SFC_DB = "sfc.db";
	
	public DaoVerifier(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
		File file = context.getDatabasePath(SFC_DB);
		Log.d(TAG, "Db location: " + file.getAbsolutePath());
	}

	public void ensureDatabaseExist() {
		SQLiteDatabase sld = null;
		Cursor cursor = null;
		String sql = "";
		try {
			sld = getReadableDatabase();
			for (TableNames tableName : TableNames.values()) {
				sql = "select DISTINCT tbl_name from sqlite_master where tbl_name = '" + tableName.getTableName() + "'";
				cursor = sld.rawQuery(sql, null);
				if (cursor != null) {
					if (cursor.getCount() == 0) {
						sql = "Creating table: " + tableName.getTableName() + " - " + tableName.getCreateCommand();
						Log.i(TAG, sql);
						sld.execSQL(tableName.getCreateCommand());
					}
					cursor.close();
				}
			}
		} catch (SQLiteException sle) {
			Log.e(TAG, "SQLite Exception: " + sle.getMessage());
		}

		if (sld != null) {
			sld.close();
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}

}
